<%@ page language="java" import="com.alibaba.fastjson.JSONArray" pageEncoding="UTF-8" %>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="com.jcraft.jsch.*" %>
<%@ page import="weaver.general.Util" %>
<%@ page import="java.io.File" %>
<jsp:useBean id="recordSet" class="weaver.conn.RecordSet" scope="page"/>
<jsp:useBean id="record" class="weaver.conn.RecordSet" scope="page"/>
<jsp:useBean id="rs" class="weaver.conn.RecordSet" scope="page"/>
<%
    JSONArray dataList = new JSONArray();
    try {
        rs.executeQuery("select dt.id,dt.doccreaterid from docdetail dt join hrmresource hr on dt.doccreaterid = hr.id " +
                "where hr.subcompanyid1=522 and doccreatedate > '2023-10-01' and doccreatedate <'2023-10-31'");
        while (rs.next()) {
            JSONObject dataJson = new JSONObject();
            String docid = Util.null2String(rs.getString("id"));
            dataJson.put("docid", docid);
            record.executeQuery("select t1.filerealpath,substr(t1.filerealpath,0,instr(t1.filerealpath, '/',-1,1)) fileapath from docimagefile t join imagefile t1 on t.imagefileid = t1.imagefileid where docid=?", docid);
            while (record.next()) {
                String remoteFilePath = Util.null2String(record.getString("filerealpath"));
                String fileapath = Util.null2String(record.getString("fileapath"));
                dataJson.put("filerealpath", remoteFilePath);
                File folder = new File(fileapath);
                if (!folder.exists()) {
                    folder.mkdirs();
                }
                File file = new File(remoteFilePath);
                if (!file.exists()) {
                    connect();
                    executeSftp(remoteFilePath, remoteFilePath);
                }
                dataList.add(dataJson);
            }
        }
        disconnect();
    } catch (JSchException | SftpException e) {
        disconnect();
        e.printStackTrace();
    }
    out.print(dataList.toJSONString());
%>
<%!
    private final String host = "10.214.11.45";
    private final int port = 22;
    private final String username = "ec";
    private final String password = "ZHlx@ec1217!";

    private Session session;

    public void connect() throws JSchException {
        JSch jsch = new JSch();
        session = jsch.getSession(username, host, port);
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();
    }

    public void disconnect() {
        session.disconnect();
    }

    public void executeSftp(String remoteFilePath, String destFilePath) throws JSchException, SftpException {
        ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
        channel.connect();
        // 读取文件内容
        channel.get(remoteFilePath, destFilePath);
        channel.disconnect();
    }


%>